package com.caiyouxi.order.service;

import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.app.model.AppOrdersBean;
import com.caiyouxi.common.Constant;
import com.caiyouxi.common.bean.QueryParams;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.cache.RedisService;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.finance.model.FinanceAccount;
import com.caiyouxi.finance.model.FinanceTradeDetail;
import com.caiyouxi.finance.model.FinanceTradeReceivable;
import com.caiyouxi.finance.model.FinanceTradeReceived;
import com.caiyouxi.finance.service.*;
import com.caiyouxi.goods.mapper.GoodsCategoryMapper;
import com.caiyouxi.goods.mapper.GoodsPropertiesConfigMapper;
import com.caiyouxi.goods.model.GoodsCategory;
import com.caiyouxi.goods.model.GoodsInfo;
import com.caiyouxi.goods.model.GoodsPropertiesConfig;
import com.caiyouxi.goods.service.GoodsInfoService;
import com.caiyouxi.order.mapper.AppOrdersMapper;
import com.caiyouxi.order.mapper.OrderMapper;
import com.caiyouxi.partner.mapper.ChannelAppConfigMapper;
import com.caiyouxi.partner.service.ChannelAppConfigService;
import com.caiyouxi.sdk.mapper.ChannelAdvanceAccountMapper;
import com.caiyouxi.sdk.mapper.ChannelAdvanceRecordMapper;
import com.caiyouxi.sdk.model.ChannelAdvanceAccount;
import com.caiyouxi.sdk.model.ChannelAdvanceRecord;
import com.caiyouxi.order.model.OrderBean;
import com.caiyouxi.order.model.SelectBean;
import com.caiyouxi.partner.model.ChannelAppConfigBean;
import com.caiyouxi.partner.model.ChannelContractBean;
import com.caiyouxi.partner.service.ChannelContractService;
import com.caiyouxi.pay.service.AccountPayService;
import com.caiyouxi.pay.service.CouponsPayService;
import com.caiyouxi.pay.service.GoodsDiscountPayService;
import com.caiyouxi.user.mapper.UserProfileMapper;
import com.caiyouxi.user.model.UserProfile;
import com.caiyouxi.util.NumUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 订单 service类
 * weichangyong
 *
 * @create 2017-08-31 15:16
 **/
@Service
public class OrderService extends BaseService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private GoodsInfoService goodsInfoService;
    @Autowired
    private FinanceTradeDetailService financeTradeDetailService;
    @Autowired
    private FinanceTradeReceivableService financeTradeReceivableService;
    @Autowired
    private FinanceAccountService financeAccountService;
    @Autowired
    private FinancePaymentDetailService financePaymentDetailService;
    @Autowired
    private FinanceTradeReceivedService financeTradeReceivedService;
    @Autowired
    private UserProfileMapper userProfileMapper;
    @Autowired
    private CouponsService couponsService;
    @Autowired
    private GoodsDiscountPayService goodsDiscountPayService;
    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;
    @Autowired
    private CouponsPayService couponsPayService;
    @Autowired
    private GoodsPropertiesConfigMapper goodsPropertiesConfigMapper;
    @Autowired
    private AccountPayService accountPayService;
    @Autowired
    private AppOrdersMapper appOrdersMapper;
    @Autowired
    private ChannelContractService channelContractService;
    @Autowired
    private ChannelAdvanceRecordMapper channelAdvanceRecordMapper;
    @Autowired
    private ChannelAdvanceAccountMapper channelAdvanceAccountMapper;
    /*danger*/
    @Autowired
    private ChannelAppConfigService channelAppConfigService;
    /*danger*/
    @Autowired
    private ChannelAppConfigMapper channelAppConfigMapper;


    /**
     * 处理支付成功订单处理
     */
    @Transactional
    public void process_order_pay_back_success (OrderBean order)throws Exception
    {
        //查看订单是否是未支付状态，如果是未支付，则更改为已支付，其它状态请小心
        if(!Constant.ORDER_STATUS_UNPAIED.equals(order.getStatus())){
            Log.d("订单状态非未支付状态，不做处理");
            return;
        }
        //更新相关流水记录信息状态
        String status = Constant.FINANCE_STATUS_RECEIVED;//已收/已交账的（待结算的）
        //更新交易流水记录信息状态
        FinanceTradeDetail ftd = financeTradeDetailService.updateFinanceTradeDetail(order,status,"ORDER");
        //更新已收已付的券记录信息
        couponsService.update_coupons_by_trade_id(ftd.getId().intValue(),Constant.COUPONS_STATUS_USED);
       
        //更新应收应付流水记录信息状态
        List<FinanceTradeReceivable> ftrs = financeTradeReceivableService.select_finance_trade_receivable_by_finance_trade_details_id(ftd.getId());
        for(FinanceTradeReceivable ftr : ftrs){
            ftr.setStatus(status);
            financeTradeReceivableService.update_finance_trade_receivable(ftr);

////------------------------通知发货（是否加至定时任务中自动发货——根据商品品类的order_finish_interval自动结算）-------------------------------
//            //处理对应的账户信息————发货
//            HashMap<String,Object> map = financeAccountService.check_account_balance(order,ftr);
////------------------------通知发货（是否加至定时任务中自动发货——根据商品品类的order_finish_interval自动结算）-------------------------------

//-------------------------------------------------------------处理开始---------------------------------------------------------------------------            
            //1 0账务+购买商品的（RECHARG_GOODS对应人GOODS对应的SELLER CASH 账户，凭空）
            FinanceAccount fa_buy1 = financeAccountService.select_finance_account_by_uiaccaac("CASH",order.getAccount_code(),0);//内置账户
            HashMap<String,Object> map1 = financeAccountService.update_finance_account(fa_buy1,order.getBuyer_user_id(),order.getTotal_amount(),Constant.USER_STATUS_CONFIRMED,order.getAccount_code(),ftr.getId(),ftr.getFinance_trade_details_id());
            if(!"SUCCESS".equals(map1.get("code"))){
                //充值异常
                Log.d("充值异常");
                return ;
            }            

            //2 内置CASE账户转到用户的CASH账户
            FinanceAccount fa_buy2 = financeAccountService.select_finance_account_by_uiaccaac("CASH",order.getAccount_code(),0);//内置账户
            HashMap<String,Object> map2 = financeAccountService.update_finance_account(fa_buy2,order.getBuyer_user_id(),- order.getTotal_amount(),Constant.USER_STATUS_CONFIRMED,order.getAccount_code(),ftr.getId(),ftr.getFinance_trade_details_id());
            if(!"SUCCESS".equals(map2.get("code"))){
                //内置账户减款
                Log.d("内置账户减款");
                return ;
            }
            FinanceAccount fa_buy3 = financeAccountService.select_finance_account_by_uiaccaac("CASH",order.getAccount_code(),order.getBuyer_user_id());//用户
            HashMap<String,Object> map3 = financeAccountService.update_finance_account(fa_buy3,order.getBuyer_user_id(),order.getTotal_amount(),Constant.USER_STATUS_CONFIRMED,order.getAccount_code(),ftr.getId(),ftr.getFinance_trade_details_id());
            if(!"SUCCESS".equals(map3.get("code"))){
                //用户余额加款异常
                Log.d("用户余额加款异常");
                return ;
            }
//-------------------------------------------------------------处理结束---------------------------------------------------------------------------
            
            //创建已收已付记录
            FinanceTradeReceived ftrd = financeTradeReceivedService.add_finance_trade_received(ftr.getTotal_amount(),ftd.getId(),ftr.getId(),Constant.FINANCE_STATUS_CREATED);

            //先创建finance_payment_detail回调返回记录
            financePaymentDetailService.add_finance_payment_detail(order.getTotal_amount(),ftrd.getId(),order.getBuyer_user_id(),"","GATEWAY");
            ftrd.setStatus(Constant.FINANCE_STATUS_FINISHED);//确认
            financeTradeReceivedService.update_finance_trade_received_by_status(ftrd);
        }
        //更新订单状态
        order.setStatus(Constant.ORDER_STATUS_PAIED);//已经确认支付的
        order.setFinished_amount(order.getTotal_amount());
        update_order(order);
//-------------------------------------------------------------处理开始---------------------------------------------------------------------------         
        //给用户购买前台商品的货币类型的账户余额充值（JCD,CB）
        Log.e("第三方充值开始");
        GoodsInfo goodsInfo = goodsInfoService.select_goodsInfo_by_id(Long.valueOf(order.getGoods_id()));
        financeAccountService.user_account_balance_recharge(order,goodsInfo);
        Log.e("第三方充值结束");
        Log.e("再进行余额支付开始");
        //走用户账户支付流程  
        Log.e("走用户账户支付流程");
        //走支付流程，不涉及货币单位转换
        order.setUp_curreny_code(null);
        ResData rd = accountPayService.account_pay(order);
        if("SUCCESS".equals(rd.getCode())){
            //通知游戏方发货成功
            Log.e("用户账户支付流程成功");
        }else{
            //通知游戏方发货失败
            Log.e("用户账户支付流程失败");
        }
        Log.e("再进行余额支付结束");
//-------------------------------------------------------------处理结束---------------------------------------------------------------------------

        
//        上面account_pay余额支付已经更改订单状态
//        //更新订单状态
//        order.setStatus(Constant.ORDER_STATUS_FINISHED);//已经确认完成
//        order.setFinished_amount(order.getTotal_amount());
//        update_order(order);
//
//        //更新缓存
//        redisService.set("order" + order_id, order);
    }

    /**
     * 处理支付失败订单处理
     * @param order_id
     */
    public void process_order_pay_back_faild(String order_id)
    {
        //暂不需要处理
    }

    public OrderBean get_order_by_id(String id) {
        String key = "ORDER_KEY_ID_" + id;
        OrderBean ob = (OrderBean) redisService.get(key);
        if(ob == null){
            ob = orderMapper.get_order_by_id(id);
            redisService.set(key, ob);
        }
        return ob;
    }

    /**
     * 订单参数校验
     */
    public boolean check_order_mess(OrderBean bean){
        if(StringUtils.isEmpty(bean.getTitle())){
            Log.d("title标题为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getGoods_id())){
            Log.d("goods_id商品编号为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getGoods_category_id())){
            Log.d("goods_category_id商品品类为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getGoods_version())){
            Log.d("version版本号为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getMarket_price())){
            Log.d("market_price定价为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getPrice())){
            Log.d("price售价为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getUnit())){
            Log.d("unit商品单位为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getNum())){
            Log.d("num商品件数为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getCurrency_code())){
            Log.d("currency_code货币代码为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getAccount_code())){
            Log.d("account_code专用账户代码为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getBuyer_user_id())){
            Log.d("buyer_user_id买家编号为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getBuyer_username())){
            Log.d("buyer_username买家用户名为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getSeller_user_id())){
            Log.d("seller_user_id卖家编号为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getSeller_username())){
            Log.d("seller_username卖家用户名为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getTotal_amount())){
            Log.d("total_amount订单金额为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getFinished_amount())){
            Log.d("finished_amount已完成的金额为空");
            return false;
        }
        if(StringUtils.isEmpty(bean.getRemark())){
            Log.d("remark订单备注为空");
            return false;
        }
        return true;
    }

    /**
     * 校验订单properties属性信息
     */
    public boolean check_order_properties(OrderBean bean){
        Log.d("商品Id" + bean.getGoods_id());
        GoodsInfo obs = goodsInfoService.select_goods_info_on_usefull(bean.getGoods_id());
        if(obs == null || !"ON".equals(obs.getStatus())){
            Log.d("无此商品或商品状态不可用" + obs == null ? "" : obs.getStatus());
            return false;
        }
        Integer category_id = obs.getCategory_id();//商品品类
        HashMap<String, Object> map = new HashMap();
        map.put("category_id",category_id);
        map.put("apply_to","ORDER");//GOODS：新增商品时需要填写该属性；ORDER：下单时需要填写这些属性；DELIVER：发货时需要填写这些属性。
        List<GoodsPropertiesConfig> gpcs = goodsPropertiesConfigMapper.select_goods_properties_config_by_category_id_and_apply_to(map);
        String properties = bean.getProperties();//校验订单的properties
        if(!StringUtils.isEmpty(properties)){
            JSONObject jsb = JSONObject.parseObject(properties);
            for(GoodsPropertiesConfig gpc : gpcs){
                JSONObject jos = JSONObject.parseObject(gpc.getConfig());
                Integer min = jos.getInteger("min");
                Integer max = jos.getInteger("max");
//                String type = jos.getString("type");
//                String keyValue = null;
//                switch (type){
//                    case "TEXT":
//                        keyValue = jsb.getString(gpc.getKey());
//                }
                String keyValue = jsb.getString(gpc.getKey());
                if(min > 0){
                    if(StringUtils.isEmpty(keyValue)){
                        Log.d(gpc.getKey() + "值为空");
                        Log.d("订单校验失败");
                        return false;
                    }
                }
                if(max < keyValue.length()){
                    Log.d(gpc.getKey() + "字段值超长");
                    Log.d("字段值超长");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 创建订单信息
     */
    public OrderBean add_order(OrderBean bean)
    {
        //根据app_id查询GoodsInfo获取相关参数
        try {
            GoodsInfo gInfo = goodsInfoService.select_goodsInfo_by_id(Long.valueOf(bean.getGoods_id()));
            bean.setGoods_id(gInfo.getId().intValue());
            if(!StringUtils.isEmpty(gInfo.getCurrency_code())){
                bean.setCurrency_code(gInfo.getCurrency_code());
            }
            if(!StringUtils.isEmpty(gInfo.getAccount_code())){
                bean.setAccount_code(gInfo.getAccount_code());    
            }
            bean.setSeller_user_id(gInfo.getSeller_user_id());

            UserProfile userProfile = userProfileMapper.get_by_id(gInfo.getSeller_user_id());
            bean.setSeller_username(userProfile == null ? "" : (userProfile.getUsername() == null ? "" : userProfile.getUsername()));

            bean.setGoods_version(gInfo.getVersion());
            bean.setGoods_category_id(gInfo.getCategory_id());
            bean.setMarket_price(gInfo.getMarket_price());
            bean.setPrice(gInfo.getPrice());
            bean.setUnit(gInfo.getUnit());
            Integer num = bean.getTotal_amount() / gInfo.getPrice();
            bean.setNum(num);//件数
//        bean.setFinished_amount(bean.getTotal_amount());
            bean.setFinished_amount(0);
            JSONObject jsb = new JSONObject();
            jsb.put("app_order_id", bean.getApp_order_id());
            bean.setProperties(jsb.toJSONString());
            bean.setTitle(gInfo.getTitle());
            bean.setBuyer_username(userProfileMapper.get_by_id(bean.getBuyer_user_id()).getUsername());

            //校验买家卖家账户及账号
            if (!check_mess(bean)) {
                //买家卖家账户异常
                return null;
            }

            //校验库存
            if (!goodsInfoService.check_goods_num(gInfo, num)) {
                Log.d("商品库存不足");
                return null;
            }

            //校验商品
            if (!goodsInfoService.check_goods_mess(bean)) {
                Log.d("商品校验失败");
                return null;
            }

            //订单参数校验
//        Log.d("bean的信息：" + bean.toString());
        boolean flagOrder = check_order_mess(bean);
        if(!flagOrder){
            //订单信息校验未通过
            Log.d("订单信息校验未通过，缺少必要的参数");
            return null;
        }

        if(!check_order_properties(bean)){
            //订单信息校验未通过
            Log.d("订单信息校验未通过，缺少必要的参数");
            return null;
        }

            //创建对应的流水记录
            try {
                create_mess(bean);
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("创建订单异常" + e.getMessage());
                return null;
            }
            return bean;
        }catch (Exception e)
        {
            Log.e("下单异常.."+e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 创建对应的流水记录——下单
     */
    @Transactional
    public void create_mess (OrderBean bean) throws Exception{
        //先判断是否减库存
        GoodsInfo gInfo = goodsInfoService.check_stock(bean.getGoods_id().longValue(),bean.getNum(),"ORDERED");
        
        //创建订单
        bean.setId("1" + NumUtil.generate_number(5));
        bean.setStatus(Constant.ORDER_STATUS_UNPAIED);//创建后等待用户支付
        bean.setCreate_time(new Date());
        bean.setUpdate_time(new Date());

        //将订单信息加入缓存
        redisService.set("order" + bean.getId(),bean);

        orderMapper.insert_into_order(bean);

        //折扣、券支付
        Integer end_amount = get_end_amount_by_coupons_goodsdiscount(bean,gInfo);//剩余待支付
        bean.setTotal_amount(end_amount);//剩余待支付
        bean.setFinished_amount(bean.getTotal_amount() - end_amount);//已支付金额

        //更新最终需结算的金额
        update_order(bean);

    }

    /**
     * 订单更新
     */
    public void update_order(OrderBean order){
        orderMapper.updateOrder(order);
    }

    /**
     * 校验买家卖家账户
     * @param bean
     * @return
     */
    public boolean check_mess(OrderBean bean){
        //校验买家账户
        if(!financeAccountService.check_buy_finance_account_mess(bean)){
            //买家账户异常
            Log.d("买家账户异常");
            return false;
        }
        //校验买家账号
        if(userProfileMapper.get_by_id(bean.getBuyer_user_id()) == null || !"NORMAL".equals(userProfileMapper.get_by_id(bean.getBuyer_user_id()).getStatus())){
            //买家账号异常
            Log.d("买家账号异常");
            return false;
        }

        //检验卖家账户
        if(!financeAccountService.check_sell_finance_account_mess(bean)){
            //卖家账户异常
            Log.d("卖家账户异常");
            return false;
        }
        //检验卖家账号

        if(userProfileMapper.get_by_id(bean.getSeller_user_id()) == null || !"NORMAL".equals(userProfileMapper.get_by_id(bean.getSeller_user_id()).getStatus())){
            //卖家账号异常
            Log.d("卖家账号异常");
            return false;
        }
        return true;
    }

    /**
     * 结算
     */
    public void order_finish_interval(OrderBean order){
        GoodsInfo gInfo = goodsInfoService.select_goodsInfo_by_id(Long.valueOf(order.getGoods_id()));
        if(gInfo == null){
            return ;
        }
        GoodsCategory goodsCategory = goodsCategoryMapper.select_goods_category(gInfo.getCategory_id());
        //判断时间
//        order_pay_expire_interval	    			创建订单后超时未支付自动取消订单的间隔。单位分钟。默认为30分钟。
//        order_deliver_expire_interval	    		支付后未发货或发货失败的自动取消订单的间隔。单位分钟。默认为24小时
//        order_finish_interval	int	 	 	 		订单发货后，交易明细自动结算的时间间隔。从订单状态变更为已发货后，经过多少分钟进入自动结算流程，将款项给卖家。单位分钟。
        Calendar car = Calendar.getInstance();
        Date nowDate = new Date();
        car.setTime(order.getCreate_time());
        Integer order_pay_expire_interval = goodsCategory.getOrder_pay_expire_interval();
        Integer order_deliver_expire_interval = goodsCategory.getOrder_deliver_expire_interval();
        Integer order_finish_interval = goodsCategory.getOrder_finish_expire_interval();
        if(Constant.ORDER_STATUS_UNPAIED.equals(order.getStatus())){
            //未支付的订单
            car.add(Calendar.MINUTE,order_pay_expire_interval);//创建时间加对应设置的分钟
            if(car.getTime().before(nowDate)){
                cancel_order(order);
                Log.d("订单已取消");
                return ;
            }
        }
        if(Constant.ORDER_STATUS_PAIED.equals(order.getStatus())){
            //已支付的订单（未发货或发货失败）
            car.add(Calendar.MINUTE,order_deliver_expire_interval);//创建时间加对应设置的分钟
            if(car.getTime().before(nowDate)){
                cancel_order(order);
                Log.d("订单已取消");
                return ;
            }
        }
        //发货状态？订单表缺状态

    }

    /**
     * 取消订单，更新对应相关流水状态
     * @param order
     */
    public void cancel_order(OrderBean order){
        //超过时间未支付——更新订单状态为用户未支付，自动撤销
        order.setStatus(Constant.ORDER_STATUS_CANCLED);
        order.setUpdate_time(new Date());
        update_order(order);

        //更新对应财务流水
        //更新交易流水记录信息状态
        FinanceTradeDetail ftd = financeTradeDetailService.updateFinanceTradeDetail(order,Constant.FINANCE_STATUS_CANCELLED,"ORDER");//已取消/已撤销的
        //更新已收已付的券记录信息
        couponsService.update_coupons_by_trade_id(ftd.getId().intValue(),Constant.COUPONS_STATUS_NORMAL);//券被恢复
        //更新应收应付流水记录信息状态
        List<FinanceTradeReceivable> ftrs = financeTradeReceivableService.select_finance_trade_receivable_by_finance_trade_details_id(ftd.getId());
        for(FinanceTradeReceivable ftr : ftrs){
            ftr.setStatus(Constant.FINANCE_STATUS_CANCELLED);
            financeTradeReceivableService.update_finance_trade_receivable(ftr);
        }
    }

    /**
     * 创建流水，折扣、券支付
     * @param bean
     * @param gInfo
     * @return
     */
    public Integer get_end_amount_by_coupons_goodsdiscount(OrderBean bean,GoodsInfo gInfo){
        Integer totalAmount = bean.getTotal_amount();//商品总价
        //创建交易流水

        String currency_code = bean.getCurrency_code();
        String account_code = bean.getAccount_code();
        Integer buy_user_id = bean.getBuyer_user_id();
        Integer sell_user_id = bean.getSeller_user_id();
        FinanceTradeDetail ftd = financeTradeDetailService.add_finance_trade_details(bean.getId(),currency_code,"ORDER",account_code,buy_user_id,sell_user_id,totalAmount,bean.getTitle());

        //---------------------目前款项仅是商品--------------------------
        JSONObject jon = new JSONObject();
        jon.put("GOODS",bean.getTotal_amount());
        bean.setFund_json(jon.toJSONString());
        //---------------------目前款项仅是商品--------------------------
        
        // /根据对应的款项类型来生成应收应付记录
        JSONObject jsons = JSONObject.parseObject(bean.getFund_json());
        JSONObject couponids = JSONObject.parseObject(bean.getCoupons_ids());
        Set<String> keys = jsons.keySet();
        Integer end_amount = 0;
        Integer every_key_value = 0;
        for(String key : keys){
            //创建应收应付记录    key对应款项    jsons.getInteger(key)对应金额
            FinanceTradeReceivable ftr = financeTradeReceivableService.add_finance_trade_receivable(ftd.getId(),key,jsons.getInteger(key),sell_user_id,buy_user_id);

            //计算对应的款项折扣
//------------------------------------------------折扣处理-------------------------------------------------
            if("GOODS".equals(key)){
                //只针对商品
//                totalAmount = check_goods_discount(gInfo,totalAmount,bean,ftr);
                //仅计算折扣，不创建对应流水
                //折扣后需支付的金额
                every_key_value = goodsDiscountPayService.check_goods_discount(gInfo,jsons.getInteger(key),bean,ftr,false);

                //获取商品的创建订单后的有效时间
                Calendar c = Calendar.getInstance();
                c.setTime(bean.getCreate_time());
                GoodsCategory goodsCategory = goodsCategoryMapper.select_goods_category(gInfo.getCategory_id());
                c.add(Calendar.MINUTE,goodsCategory.getOrder_pay_expire_interval());
                bean.setPay_expire_time(c.getTime());
            }else{
                //jsons.getInteger(key)是对应款项的金额
                every_key_value = jsons.getInteger(key);
            }
//------------------------------------------------折扣处理-------------------------------------------------

//-------------------------------------------------券处理--------------------------------------------
            //校验对应款项券信息是否可用
//            Integer total_end_amount = check_coupons(bean,key,totalAmount,ftr);
            if(!StringUtils.isEmpty(couponids)){
                String[] coupons_ids = couponsService.check_coupons(couponids.getString(key),key);
                for(String coupons_id : coupons_ids){
                    if(every_key_value != 0){
                        //仅计算券，不创建对应流水
                        //券处理后需支付的金额
                        every_key_value = couponsPayService.coupons_on_use(coupons_id,key,every_key_value,ftr.getFinance_trade_details_id(),ftr.getId(),bean.getBuyer_user_id(),gInfo,false);
                    }else{
                        //无需用券
                        Log.d(key + "无需用券");
                        break;
                    }
                }
            }
            end_amount += every_key_value;//所有款项还需支付的金额
//-------------------------------------------------券处理--------------------------------------------
        }
        //剩余待支付end_amount
        return end_amount;
    }





















/*======================================================订单业务开始===============================================================*/
    /**
     *
     * @author wushihao
     * @create 2017-12-15
     * 获取订单列表
     * @param bean
     * */
    public ResData get_orders_list(OrderBean bean){
        QueryParams pageList = new QueryParams();
        Integer pageSize = null;
        try {
            pageSize = Integer.parseInt(redisService.get("sys.pagesize").toString());
            //pageSize =20;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            pageSize = 20;//如果redis失败手动设置pagesize为20；
        }
        if(bean.getPage_size() == 0){
            bean.setPage_size(pageSize);
        }
        if(bean.getPagesize() == null || bean.getPagesize() == 0){
            bean.setPagesize(pageSize);
        }
        if(bean.getPages() == null){
            bean.setPages(0);
        }
        List<OrderBean> list = orderMapper.get_orders_list(bean);
        Integer total = orderMapper.get_orders_count(bean);
        pageList.setList(list);
        pageList.setTotal(total);
        return page_list(pageList);
    }

    /**
     * 查询订单详情1
     * */
    public ResData get_orders_info(OrderBean bean){
        return success(orderMapper.get_orders_info(bean));
    }

    /**
     * 查询订单详情2
     * */
    public ResData get_orders_infos(SelectBean bean){
        return success(orderMapper.get_orders_infos(bean));
    }

    /**
     * 查询优惠券
     * */
    public ResData get_coupon_type(OrderBean bean){
        return success(orderMapper.get_coupon_type(bean));
    }

    /**
     * 撤消订单
     * */
    public ResData revoke_order(OrderBean bean){
        Log.e("订单信息撤销开始" + bean.getId() + "状态" + bean.getStatus());
        String properties = bean.getProperties();
        if(!StringUtils.isEmpty(properties)){
            JSONObject jsb = JSONObject.parseObject(properties);
            String app_order_id = jsb.get("app_order_id") == null ? "" : jsb.get("app_order_id").toString();
            if(!StringUtils.isEmpty(app_order_id)){
                Log.e("聚合订单信息撤销开始" + app_order_id + "状态" + bean.getStatus());
                OrderService orderService = new OrderService();
                AppOrdersBean appOrder = orderService.get_app_order_by_id(Long.valueOf(app_order_id));
                if(appOrder != null){
                  //  appOrderService.concleOrder(appOrder);
                    Log.e("聚合订单信息撤销结束" + app_order_id + "状态" + bean.getStatus());
                }else{
                    Log.e("order无关联的聚合订单信息app_order_id" + app_order_id);
                }
            }else{
                Log.e("order无关联的聚合订单信息properties" + properties);
            }
        }else{
            Log.e("order无关联的聚合订单信息");
        }
        //orderService.cancel_order(bean);
        Log.e("订单信息撤销结束" + bean.getId() + "状态" + bean.getStatus());
        return null;
    }






    /**
     * 获取某个订单信息
     * */
    public AppOrdersBean get_app_order_by_id(Long beanId){
        String key = "APP_ORDERS_BEAN_" + beanId;
        AppOrdersBean aob = (AppOrdersBean) redisService.get(key);
        if(aob == null){
            aob = appOrdersMapper.select_app_orders(beanId);
            redisService.set(key,aob);
        }
        return aob;
    }



    /**
     * 取消订单处理
     */
    @Transactional
    public synchronized void concleOrder(AppOrdersBean appOrder){
        //根据channel_id、app_id查询cp分成表channel_contract
//        HashMap<String, Object> m = new HashMap();
//        m.put("channel_id", appOrder.getChannel_id());
//        m.put("app_id", appOrder.getApp_id());
//        ChannelContractBean cpb = channelContractMapper.select_channel_contract_on_map(m);
        ChannelContractBean cpb = channelContractService.get_channel_contract_bean(appOrder.getChannel_id(),appOrder.getApp_id());
        if(1 == cpb.getNeed_advances()){
            ChannelAdvanceRecord channelAdvanceRecord = channelAdvanceRecordMapper.select_channel_advance_record_by_relate_object_id(appOrder.getId().toString());
            if(!StringUtils.isEmpty(channelAdvanceRecord)){
                appOrder.setStatus("CANCLED");//用户未支付订单被撤销时，该条财务流水自动被撤销。
                appOrder.setComplete_time(new Date());//订单取消时间
                appOrdersMapper.update_app_orders(appOrder);//更新订单状态
                Log.d("更新订单处理完毕CANCLED");

                Integer amount = channelAdvanceRecord.getAmount();//支付的金额

                //订单信息的渠道ID即为合作伙伴编号即parentID
                ChannelAdvanceAccount channelAdvanceAccount = channelAdvanceAccountMapper.select_channel_advance_account(appOrder.getChannel_id());
                Integer balance = channelAdvanceAccount.getBalance();//账户余额
                Integer close_balance = channelAdvanceAccount.getClose_balance();
                //更新预存款余额
                Log.d("预存款账户余额" + balance);
                channelAdvanceAccount.setBalance(balance + amount);
                channelAdvanceAccountMapper.update_channel_advance_account(channelAdvanceAccount);
                Log.d("更新预存款账户余额完毕" + (balance + amount));

                Log.d("渠道支付状态——先查询缓存");
                ChannelAppConfigBean search = new ChannelAppConfigBean();
                search.setChannel_id(appOrder.getChannel_id());
                search.setApp_id(appOrder.getApp_id());
                ChannelAppConfigBean   chCB =channelAppConfigService.get_channel_app_config(search);
                if (1 != chCB.getPay_status()) {
                    //渠道未开启
                    if((balance + amount) >= close_balance){
                        //加上取消的金额，大于等于阈值的开启渠道通道
                        Log.d("余额不低于阈值，开启渠道支付通道");
                        chCB.setPay_status(1);//0关闭1开启
                        chCB.setUpdate_time(new Date());
                        channelAppConfigMapper.update_channel_config(chCB);
                    }else{
                        Log.d("余额仍低于阈值，无需开启");
                    }
                }else{
                    Log.d("渠道未关闭无需判断是否处理开启");
                }

                //处理流水。考虑事务
                HashMap<String, Object> map = new HashMap();
                map.put("relate_object_id", appOrder.getId().toString());//关联对象编号
                map.put("status", "CANCLED");//用户未支付订单被撤销时，该条财务流水自动被撤销。
                map.put("update_time",new Date());//更新时间
                channelAdvanceRecordMapper.update_channel_advance_record_status(map);
                Log.d("更新流水状态完毕");
            }else{
                Log.d("无对应的财务流水，暂不处理" + appOrder.getId());
            }
        }else{
            Log.d("需要该渠道支付预付款：否" + cpb.getNeed_advances());
            appOrder.setStatus("CANCLED");//用户未支付订单被撤销时，该条财务流水自动被撤销。
            appOrder.setComplete_time(new Date());//订单取消时间
            appOrdersMapper.update_app_orders(appOrder);//更新订单状态
            Log.d("更新订单处理完毕CANCLED");
        }
    }
    /*======================================================订单业务结束===============================================================*/
}
